

#include <vfs.h>
#include <gfx/mesh.h>
#include <gfx/multimesh.h>
#include <manager/meshmanager.h>
#include <assert.h>

ceMeshManager* ceMeshManager::static_instance = 0;

ceMeshManager::ceMeshManager()
{
}

ceMeshManager::~ceMeshManager ()
{
  std::map<std::string, ceMesh*>::iterator mit;
  for (mit = _meshes.begin (); mit != _meshes.end(); ++mit)
		{
      ceMesh* mesh = mit->second;
      CE_UNSET(mesh);
		}

  std::map<std::string, ceMultiMesh*>::iterator mmit;
  for (mmit = _multiMeshes.begin (); mmit != _multiMeshes.end(); ++mmit)
    {
      ceMultiMesh* mesh = mmit->second;
      CE_UNSET(mesh);
    }

  _meshes.clear();
	_multiMeshes.clear();
}

ceMeshManager* ceMeshManager::Get()
{
  if (!ceMeshManager::static_instance)
    {
      ceMeshManager::static_instance = new ceMeshManager();
      ceMeshManager::static_instance->AddRef();
    }
  return ceMeshManager::static_instance;
}

ceMeshManager* ceMeshManager::Reset(ceMeshManager *meshManager)
{
  if (!meshManager)
    {
      meshManager = new ceMeshManager();
    }

  CE_SET(ceMeshManager::static_instance, meshManager);
  return ceMeshManager::static_instance;
}


void ceMeshManager::AddMesh(const std::string &name, ceMesh *mesh)
{
  assert (mesh);
  CE_SET(_meshes[name], mesh);
}

void ceMeshManager::AddMesh(const std::string &name, ceMultiMesh *mesh)
{
  assert (mesh);
  CE_SET(_multiMeshes[name], mesh);
}


ceMesh* ceMeshManager::GetMesh(const std::string &name, bool load, bool add)
{
  std::map<std::string, ceMesh*>::iterator it;
  it = _meshes.find (name);
  if (it != _meshes.end())
    {
      return it->second;
    }

	return 0;
}



ceMultiMesh* ceMeshManager::GetMultiMesh(const std::string &name, bool load, bool add)
{
  std::map<std::string, ceMultiMesh*>::iterator it;
  it = _multiMeshes.find (name);
  if (it != _multiMeshes.end())
    {
      return it->second;
    }

	if (load)
		{
			assert (false);
			return 0;
			/*
      ceXMLDataLoader dl;
      ceMultiMesh* mesh = dl.LoadMultiMesh (engine, ceVFS::Get()->Open(name));
			if (mesh && add)
				{
					AddMesh(name, mesh);
				}
			return mesh;
			*/
		}
	return 0;
}

